import json
import os

if __name__ == '__main__':

    test_json_raw = json.load(open("data/annotations/side_test.json", "r"))
    test_json_half = json.load(open("data/annotations/side_half_test.json", "r"))
    test_json_result = json.load(open("results/side/model1half.bbox.json", "r"))
    save_json = "results/side/model1.bbox.json"

    json_dict = []
    imgid2name = {}
    imgid2width = {}
    imgname2rawid = {}
    imgid2rawid = {}

    for imageinfo in test_json_raw['images']:
        imgname2rawid[imageinfo['file_name']] = imageinfo['id']

    for imageinfo in test_json_half['images']:
        imgid2name[imageinfo['id']] = imageinfo['file_name']
        imgid2rawid[imageinfo['id']] = imgname2rawid[imageinfo['file_name'][:-5] + '.jpg']
        imgid2width[imageinfo['id']] = imageinfo['width']

    for anno in test_json_result:
        imgid = imgid2rawid[anno["image_id"]]
        if imgid2name[anno["image_id"]][-5] == 'r':
            anno['bbox'][0]+= imgid2width[anno["image_id"]]
        new_anno = {"image_id": imgid, "bbox": anno['bbox'], "score": anno['score'], "category_id": 1}
        json_dict.append(new_anno)

    json_fp = open(save_json, 'w')
    json_str = json.dumps(json_dict)
    json_fp.write(json_str)
    json_fp.close()
